/*数据库操作*/
/*http请求*/
const rp = require('request-promise');
const lodash = require('lodash');
const xlsx = require('node-xlsx');
const basics_db = require('../../dbhelper/basics_db');
const schedule = require('node-schedule');
/*根参数*/
const appkey = '25362818';
const appsecret = '38c134ab6dae9fe6223f5e977fce04a3';

/*通用工具*/
const jason_tools = require('../../../utils/jason_tools.js');

const WYTbcats = 'http://api.vephp.com/tbcats';
const WYorders = 'http://apiorder.vephp.com/orderdetails';
const WYvekey = 'V00001109Y18343095';

/**
 * 导入订单的excel文档
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.orderExcel = async (ctx, next) => {
    /*参数声明*/
    let token = ctx.request.header.token;
    //校验
    if (token != "1q2w3e4") {
        ctx.body = {
            code: 0,
            message: '警告！已触发身份报警！'
        };
        return;
    }
    //导入Excel，xlsx格式
    let file = ctx.request.files.file;
    var fileObj = xlsx.parse(file.path);
    let fileData = fileObj[0].data;
    
    let result = [];
    var obj = {};
    // 字段过滤 fileData.slice(1), 
    lodash.forEach(fileData.slice(1), (d) => {
        let objItem = d[25] + '_' + d[3]
        if(!obj[objItem]){
            result.push({ creatTime: d[0],clickTime: d[1],commodity: d[2],commodityId: d[3],thisShop: d[5],number: d[6],state: d[8],payment: d[12], estimate_m: d[13], income_p: d[17], trade_id: d[25], pid: d[29], platformName: d[30] });
            obj[objItem] = true;
       }
    });

    let data = await basics_db.insert('order',result)
    ctx.body = data;
}

/**
 * 导表开始时间查询
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.queryStartDate = async (ctx, next) => {
    /*参数声明*/
    let token = ctx.request.header.token;
    //校验
    if (token != "1q2w3e4") {
        ctx.body = {
            code: 0,
            message: '警告！已触发身份报警！'
        };
        return;
    }

    let result;
    /*数据操作*/
    result = await basics_db.findSort('order',{state:{$in: ['订单付款']}},{'creatTime':1})
    return ctx.body = {
        code: 1,
        data: result
    };
}

/**
 * 清空订单 -- 全部清除
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.clearOrders = async (ctx, next) => {
    /*参数声明*/
    let token = ctx.request.header.token;
    //校验
    if (token != "1q2w3e") {
        ctx.body = {
            code: 0,
            message: '警告！已触发身份报警！'
        };
        return;
    }

    let result;
    /*数据操作*/
    result = await basics_db.dropCollection('order')
    return ctx.body = {
        code: 1,
        data: result
    };
}

/**
 * 删除指时间后订单
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.clearOrderBytime = async (ctx, next) => {
    /*参数声明*/
    let token = ctx.request.header.token;
    let query = ctx.request.body;
    //校验
    if (token != "1q2w3e4") {
        ctx.body = {
            code: 0,
            message: '警告！已触发身份报警！'
        };
        return;
    }

    let result;
    /*数据操作*/
    result = await basics_db.remove('order',{'creatTime': {$gte: query.startDate}})
    return ctx.body = {
        code: 1,
        data: result
    };
}


/**
 * 淘宝二级分类
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.insertTbcats = async (ctx, next) => {
    /*参数声明*/
    let token = ctx.request.header.token;
    //校验
    if (token != "1q2w3e4") {
        ctx.body = {
            code: 0,
            message: '警告！已触发身份报警！'
        };
        return;
    }
    
    /*传参声明*/
    let params = {
        vekey: WYvekey
    };
    /*函数体*/
    let options = {
        uri: WYTbcats,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise',
        },
        json: true // Automatically parses the JSON string in the response
    };
    /*请求体*/
    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            return ctx.body = {
                ok: 0,
                message: err
            };
        });

        if (res.data.length) {
            await basics_db.dropCollection('cats')
        }

        let data = await basics_db.insert('cats',res.data)
        return ctx.body = data;
}


/**
 * 淘宝客订单定时导入功能
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.setTimeOrder = async (ctx, next) => {
    /*参数声明*/
    let token = ctx.request.header.token;
    let query = ctx.request.body;
    //校验
    if (token != "1q2w3e4") {
        ctx.body = {
            code: 0,
            message: '警告！已触发身份报警！'
        };
        return;
    }
    let startTimeStm = new Date(query.startDate).getTime();
    let endTimeStm = startTimeStm + 1000*60*60*3;
    console.log(query.startDate,startTimeStm,endTimeStm)
    
    let startTime = jason_tools.formatDate(startTimeStm,'yyyy-MM-dd hh:mm:ss');
    let endTime = jason_tools.formatDate(endTimeStm,'yyyy-MM-dd hh:mm:ss');
    console.log(startTime,endTime)
    
    
    /*传参声明*/
    let params = {
        vekey: WYvekey,
        start_time: startTime,
        end_time: endTime
    };
    /*函数体*/
    let options = {
        uri: WYorders,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise',
        },
        json: true // Automatically parses the JSON string in the response
    };
    /*请求体*/
    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            return ctx.body = {
                ok: 0,
                message: err
            };
        });
        return ctx.body = res;
}

/**
 * 淘宝登录授权 -- 获取sessionKey
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.oauth2 = async (ctx, next) => {
    /*校验*/
    let query = ctx.request.header.token;
    if (query != "1q2w3e4") {
        ctx.body = {
            code: 0,
            message: '警告！已触发身份报警！'
        };
        return;
    }
    /*参数声明*/
    let body = ctx.request.body;
    /*函数体*/
    let options = {
        method: 'POST',
        uri: 'https://oauth.taobao.com/token',
        form: {
            'client_id': appkey,
            'client_secret': appsecret,
            'grant_type': 'authorization_code',
            'code': body.code,
            'redirect_uri': body.uri,
            'state': body.state,
            'view': 'web'
        },
        //simple: false,
        json: true // Automatically parses the JSON string in the response
    };
    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            res = err;
        });
    
    if (!res.error) {
        res.name = 'sessionKey'
        let data = await basics_db.insert('system',res)
        ctx.body = data;
    } else {
        return ctx.body = res;
    }
    
}

/**
 * 数据通讯测试
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.dataTest = async (ctx, next) => {
    /*数据操作*/
    let data = await basics_db.findOne('user',{'name': '张海芳'})
    return ctx.body = data;
}
